package com.ruoyi.common.utils.wx;

import com.ruoyi.common.config.wx.WxCpConfiguration;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;

@Slf4j
public class SendWxCpMsgUtil {

    public static String sendTextMsg(Integer agentId, String userId, String msg) throws WxErrorException {
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        return sendMsg(userId, msg, wxCpService);
    }

    private static String sendMsg(String userId, String msg, WxCpService wxCpService) throws WxErrorException {
        WxCpMessage wxCpMessage = WxCpMessage.TEXT().toUser(userId).content(msg).build();
        WxCpMessageSendResult send = wxCpService.getMessageService().send(wxCpMessage);
        return send.getMsgId();
    }

    public static String sendTextMsgByUserPhoneNum(Integer agentId, String phoneNum, String msg) throws WxErrorException {
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        String userId = wxCpService.getUserService().getUserId(phoneNum);
        String s = sendMsg(userId, msg, wxCpService);
        return s;
    }

}
